<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
      // pieCharData:{
      //   jobSuccess: this.chartData.jobSuccess,
      //   jobFail: this.chartData.jobFail,
      //   jobRunning: this.chartData.jobRunning
      // }
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    setOptions(charData) {
      this.chart.setOption({
        title: {
          // 标题及位置
          text: '成功比例图',
          left: 'center'
        },
        tooltip: {
          // 悬停样式
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          // 图例，竖排
          left: 'center',
          bottom: '0'
          // orient: "vertical"
        },
        calculable: true,
        series: [
          {
            // 提示框标题
            name: '成功比例图',
            type: 'pie',
            roseType: 'radius',
            // 各部分饼占父元素百分比
            radius: [15, 95],
            center: ['50%', '50%'],
            data: [
              { value: charData.jobSuccess, name: '成功' },
              { value: charData.jobFail, name: '失败' },
              { value: charData.jobRunning, name: '进行中' }
            ],
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.el-col-lg-8 {
  width: 50%;
}
</style>
